package br.fagoc.easyds.ui.code;

import java.awt.Color;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

import br.fagoc.easyds.util.Delay;

public class TextAreaController {
	
	private JTextArea textArea;
	
	private Highlighter highlighter;
	private Highlighter.HighlightPainter yellowPainter;


	public TextAreaController(JTextArea textArea){
		this.textArea = textArea;
		highlighter = textArea.getHighlighter();
        yellowPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(0xEDED8D));
	}
	
	public void showText(String path){
		try {
			clearText();
			
			InputStream in = getClass().getResourceAsStream(path);
			Reader fr = new InputStreamReader(in, "utf-8");
			
			while(true){
				int character = fr.read();
				
				if(character == -1){
					break;
				}
				char[] c = new char[1];
				c[0] = (char) character;
				textArea.append(new String(c));
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		textArea.revalidate();
		textArea.repaint();
		textArea.revalidate();
		textArea.repaint();
		textArea.setCaretPosition(0);
	}
	
	public void clearText(){
		textArea.setText("");
		textArea.revalidate();
		textArea.repaint();
		textArea.revalidate();
		textArea.repaint();
	}
	
	public void markText(int start, int end){
        try {
        	unmarkText();
			highlighter.addHighlight(start, end, yellowPainter);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
        
		scrollTo(start, end);

		textArea.revalidate();
		textArea.repaint();
		textArea.revalidate();
		textArea.repaint();
	}
	
	public void unmarkText(){
		highlighter.removeAllHighlights();
		textArea.revalidate();
		textArea.repaint();
		textArea.revalidate();
		textArea.repaint();
	}
	
	private void scrollTo(int start, int end){
		int lastPosition = textArea.getText().length();
		
		try {
			textArea.scrollRectToVisible(textArea.modelToView(lastPosition));
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		
		try {
			textArea.scrollRectToVisible(textArea.modelToView(start));
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
}
